package org.dev_common.func;

import static java.util.Calendar.HOUR_OF_DAY;
import static java.util.Calendar.MINUTE;
import static java.util.Calendar.SECOND;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Calendar;
import java.util.Date;
import java.util.concurrent.TimeUnit;

public class Functions {

    public static final int yyyy_mm_dd_length = "2017-11-06".length();

    public static String getDateFromRequestTime(String requstTime) {
        if (null == requstTime || requstTime.length() < yyyy_mm_dd_length) {
            return "";
        }
        return requstTime.substring(0, yyyy_mm_dd_length);
    }

    public static long toTheNextDayInmillis() {
        return getNextDay(0).getTime() - System.currentTimeMillis();
    }

    /**
     * default time-zone etc.
     * 
     * @param hour
     * @return
     */
    public static Date getNextDay(int hour) {
        Calendar calendar = Calendar.getInstance();
        // calendar.setTime(new Date());
        calendar.set(HOUR_OF_DAY, hour);
        calendar.set(MINUTE, 0);
        calendar.set(SECOND, 0);
        return new Date(calendar.getTimeInMillis() + TimeUnit.DAYS.toMillis(1));
    }

    public static int toInt(String str, int defaultValue) {
        if (str == null) {
            return defaultValue;
        }
        try {
            return Integer.parseInt(str);
        } catch (NumberFormatException nfe) {
            return defaultValue;
        }
    }

    public static boolean isBlank(String source) {
        return source == null || source.trim().isEmpty();
    }

    public static String getHostName() {
        String host = "";
        try {
            host = (InetAddress.getLocalHost()).getHostName();
        } catch (UnknownHostException uhe) {
            host = uhe.getMessage();
            if (host != null) {
                int colon = host.indexOf(':');
                if (colon > 0) {
                    host.substring(0, colon);
                }
            }
        }
        return host;
    }

    /**
     * 获取next days日零时(not so effective)
     * @param days
     * @return
     */
    public static Date getAfterDay(int days) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date(System.currentTimeMillis() + TimeUnit.DAYS.toMillis(days)));
        calendar.set(HOUR_OF_DAY, 0);
        calendar.set(MINUTE, 0);
        calendar.set(SECOND, 0);
        return new Date(calendar.getTimeInMillis() + TimeUnit.DAYS.toMillis(1));
    }
    
    public static void sleep(int millis) {
        try {
            Thread.sleep(millis);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
